package com.ntd.study.protocol.netty;

import com.ntd.study.protocol.socket.UtilCollectInterface;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class UtilNettyUdpServer implements UtilCollectInterface {
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    private final int port;
    //NioEventLoopGroup是用来处理IO操作的多线程事件循环器
    ChannelFuture channelFuture;
    private List<ChannelHandlerContext> channelHandlerContexts = new ArrayList<>();

    public UtilNettyUdpServer(int port) {
        this.port = port;
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendMsg(byte[] bytes) {
        channelHandlerContexts.forEach(channelHandlerContext -> {
//            handleSendMsg(bytes, channelHandlerContext);
        });
    }


    public void init() throws Exception {
        Bootstrap serverBootstrap = new Bootstrap();//是一个启动NIO服务的辅助启动类
        serverBootstrap.group(workerGroup)
                .channel(NioDatagramChannel.class)  // 这里告诉Channel如何接收新的连接
                .handler(new SimpleChannelInboundHandler<DatagramPacket>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
                        String req = packet.content().toString(CharsetUtil.UTF_8);//上面说了，通过content()来获取消息内容
                        log.info("服务端 - 收到消息：" + req);
                        channelHandlerContexts.add(ctx);
                        onMsg(packet.content());
                        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("服务端 - 返回：", CharsetUtil.UTF_8), packet.sender()));
                    }
                });
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
        channelFuture = serverBootstrap.bind(port).sync();// 绑定端口，开始接收进来的连接
        System.out.println("服务端启动成功...");
//        channelFuture.channel().closeFuture().sync(); // 监听服务器关闭 - netty关闭后继续执行
    }

    private void onMsg(ByteBuf content) {}

    public void close() {
        workerGroup.shutdownGracefully();
    }

    public static void main(String[] args) {
        final UtilNettyUdpServer nettyServer = new UtilNettyUdpServer(38112);
//        nettyServer.close();
    }
}
